import { getServerSideCategories, getProductDetailSvc } from '@/services/back';
import { getCategoryByPaths, stripTags } from '@/utils/common';
import ProductPage from '@/views/Product';
import { notFound } from 'next/navigation';

export async function generateMetadata({
  params,
}: {
  params: { slug: string[] };
}) {
  const { slug } = params;
  const sku = slug[0];
  const defTitle = 'my-company Product';
  let title = defTitle;
  let description = defTitle;
  let keywords = [defTitle];

  if (sku) {
    const detailRes = await getProductDetailSvc(slug.join('%2F'));
    if (detailRes.success && detailRes.data.result) {
      const detail = detailRes.data.result;
      const cateInfo = (detail.Category || '').split('>').reverse().join('-');
      title = `${detail.title} - ${cateInfo}`;
      description = stripTags(detail.desc).slice(0, 200);
      keywords = [detail.title];
    }
  }
  return {
    title,
    description,
    keywords,
  };
}

export default async function Page(props: any) {
  // console.log('=========== start app/product/page ===========');
  const categories = await getServerSideCategories();
  const slug = props?.params?.slug;
  const paths = slug?.map((p: any) => p.replace(/\.html?$/i, '')) || [];
  const searchParams = props?.searchParams;
  const currCategory = getCategoryByPaths(paths, categories);
  if (!paths?.length) {
    return notFound();
  }
  const pageTitle = 'Product Detail';
  const queryParams = {
    skus: paths.join(),
  };
  const skuInfo = undefined;

  //console.log('💡 params >> ', queryParams);
  // const skusInfo = await getServerSideProducts(queryParams);
  // .then(res => {
  //   console.log('💡 result skus >> ', res?.result?.length);
  //   skuInfo = res?.result[0];
  // });
  // console.log('💡 result skus >> ', skusInfo?.result?.length);
  // skuInfo = skusInfo?.result[0];

  return (
    <ProductPage
      {...props}
      paths={paths}
      searchParams={searchParams}
      categories={categories || []}
      pageTitle={pageTitle}
      category={currCategory}
      product={skuInfo}
    />
  );
}
